package com.tx.platform.loader.dynamic;

import com.tx.admin.noveldict.service.NovelDictService;
import com.tx.admin.noveldictdetail.pojo.vo.NovelDictDetailVO;
import com.tx.admin.noveldictdetail.service.NovelDictDetailService;
import com.tx.core.common.entity.DictVO;
import com.tx.platform.enums.DynamicDictEnum;
import com.tx.platform.loader.DictLoader;
import com.tx.redis.RedisCache;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Component;

import java.util.*;

/**
 * 动态字典——系统用户loader
 *
 * DynamicUserOptionDictLoader
 * 
 * @author sz
 * @since 2024/8/21 13:17
 * @version 1.0
 */
@Component
@RequiredArgsConstructor
public class NovelOptionDictLoader implements DictLoader {

    private final RedisCache redisCache;

    private final NovelDictDetailService dictDetailService;
    private final NovelDictService novelDictService;

    @Override
    public DynamicDictEnum getDynamicTypeCode() {
        return DynamicDictEnum.NOVEL_OPTIONS;
    }

    @Override
    public Map<String, List<DictVO>> loadDict() {
        String key = getDynamicTypeCode().getTypeCode();
        String name = getDynamicTypeCode().getName();
        if (!haveNoCacheKey()) {
            return Map.of(key, redisCache.getDictByType(key));
        }

        Map<String, List<NovelDictDetailVO>> allDicts = dictDetailService.getDetailOption();

        Map<String, List<DictVO>> result = new HashMap<>();
        allDicts.forEach((k,v)->{
            DictVO dictVO;
            List<DictVO> list = new ArrayList<>();
            for (int i = 0; i < v.size(); i++) {
                NovelDictDetailVO detailVO = v.get(i);
                //定死了ID为字典项值，codeName 字典项名(标签)  alias用value
                dictVO = DictVO.builder().id(detailVO.getNumKey().toString()).codeName(detailVO.getName()).alias(detailVO.getDictName()).sort(i + 1)
                        .sysDictTypeCode(key).detailValue(detailVO.getValue())
                        .sysDictTypeName(name).callbackShowStyle("success").isDynamic(true).isLock("F").isShow("T").build();
                list.add(dictVO);
            }
            result.put(k,list);
        });

        redisCache.putAllDict(result);
        return result;
    }

    private boolean haveNoCacheKey() {
        boolean haveNoCacheKey = Optional.ofNullable(novelDictService.getDetailOption())
                .orElse(new ArrayList<>()).stream()
                .anyMatch(s -> !redisCache.hasHashKey(s.getCode()));

        return haveNoCacheKey;
    }

    @Override
    public List<DictVO> getDict(String typeCode) {
        return loadDict().get(typeCode);
    }

}
